<template>
    <div class="container-details">
        <n-spin :show="onteShow">
            <div class="header-row">
                <h1 style="font-weight: bold;">{{ userDtailList.title }}</h1>
            </div>
            <div class="content">
                <n-divider />
                <p @click.stop="handerUpdateContent" class="mb-10 avaterName" style="font-size: 14px;"> {{ parseTime(new
                    Date(userDtailList.createTime), '{y}-{m}-{d}') }} 作者: <span class="user-name mb-5">{{
                        userDtailList.avatarName || '默认' }}</span>
                </p>
                <div ref="textRef" v-if="!editShow" class="text content-container">
                    <template v-for="(item) in userDtailList.html">
                        <p>{{ item }}</p>
                    </template>
                    <n-image v-if="userDtailList.imageUrl" style="width:100%" width="100%" :src="userDtailList.imageUrl"
                        :fallback-src="userDtailList.imageUrl" />
                </div>
                <div v-if="editShow" class="text">
                    <n-button type="info" class="mb-15 mt-10 right" size="small"
                        @click.stop="updateNote()">更新</n-button>
                    <p class="mt-10 mb-10"><n-input v-model:value="userDtailList.title" placeholder="标题怎么改？">
                        </n-input></p>
                    <n-input show-count style="height: 300px;" v-model:value="updateContent" type="textarea"
                        placeholder="今天改点什么？">
                    </n-input>
                    <n-flex class="mt-10 mb-10">
                        <span>是否置顶</span>
                        <n-switch @update:value="handleTopping" v-model:value="topping" />
                    </n-flex>
                    <n-flex v-if="updateImage" class="mt-10 mb-10">
                        <n-input   v-model:value="userDtailList.imageUrl" size="small" placeholder="图片地址" clearable />
                    </n-flex>

                </div>
            </div>
            <template #description>
                文章预载中
            </template>
        </n-spin>

    </div>
    <div class="bg"></div>
    <div class="comment-container">

        <h2 class="mt-10 mb-10">评论 <span>{{ userDtailList.comment.length ?? 0 }}</span></h2>
        <div class="comment-form">
            <div class="avatar">
                <n-avatar v-if="currentUserAvatar" :src="currentUserAvatar"></n-avatar>
                <n-avatar v-else :style="{
                    color: 'yellow',
                    backgroundColor: 'green'
                }">
                    {{ currentLoginUserName ? currentLoginUserName!.charAt(0) : '侠客'.charAt(0) }}
                </n-avatar>
            </div>
            <div class="form-box">
                <!-- 评论表单 -->
                <n-input @focus="show = true" v-model:value="commentValue" type="textarea" maxlength="1000" autosize
                    style="min-width: 50%;height: 90%;" show-count placeholder="可以骂人，但不要留情" />
                <n-button v-if="show" type="primary" class="mb-15 mt-10 right" size="small"
                    @click="hairComment">评论</n-button>
            </div>

        </div>
        <!-- 展示评论区 -->
        <div class="comment-list mt-30">
            <n-spin :show="commentShow">
                <div v-for="item in userDtailList.comment" :key="item.id" class="comment-item mb-10">
                    <div class="avatar">
                        <n-avatar v-if="item.avatar" :src="item.avatar"></n-avatar>
                        <n-avatar v-else :style="{
                            color: 'yellow',
                            backgroundColor: 'red'
                        }">

                            {{ item.commentUserName.charAt(0).toLocaleUpperCase() }}
                        </n-avatar>
                    </div>

                    <div class="info-box">
                        <p class="content-name">{{ item.commentUserName }} <span
                                :class="item.alias === '建造者' ? 'role-name' : 'user-name'">{{ item.alias }}</span></p>
                        <p class="content-text">{{ item.content }}</p>
                        <ul class="content-action">
                            <li class="content-time"> {{ formatTime(new Date(item.createTime as string)) }}</li>
                            <!-- <li class="content-time">
                            <i class="iconfont icon-dizhi fz-14"></i>
                            北京
                        </li> -->
                        </ul>
                    </div>
                </div>
            </n-spin>
        </div>

    </div>

</template>

<script setup lang="ts">
import bus from '@/utils/mitt';
import { browseUpdate, findUserCommentContent, sendComment, usrUpdateNote, findNote } from '@/apis/index';
import { formatTime, parseTime } from '@/utils/index';
import { useMessage } from 'naive-ui';
interface userComment {
    id: string | number;
    commentUserName: string;
    content: string;
    createTime?: string | null;
    alias: string;
    avatar: string
}

interface userDetailsModel<T> {
    title: string;
    html: Array<T>;
    imageUrl: string;
    createTime: string,
    avatarName: string;
    comment: userComment[]

}

interface Comment {
    noteId: string | number;
    content: string;
    alias: string;
    createTime: Date;
    avatar: string
}
const textRef: any = ref(null);
const onteShow = ref(false);
const commentShow = ref(false);
const message = useMessage()
const currentLoginUserName = localStorage.getItem('u');
const currentUserAvatar = localStorage.getItem('avatar') as string;
const commentValue = ref("");
const updateContent: any = ref('');
const topping = ref(false);
const isFlag = ref(true);
const editShow = ref(false);
const show = ref(false);
const updateImage = ref(false);
const router = useRouter();
const { query } = useRoute();
const loadingBar = useLoadingBar();

browseUpdate({
    noteId: query.id,
})

function handleTopping(value: boolean) {
    topping.value = value;
}

const userDtailList = ref<userDetailsModel<Array<any>[]>>(
    {
        title: "",
        html: [],
        imageUrl: '',
        avatarName: "",
        createTime: '',
        comment: []
    }
)
// 更新内容 支持修改图片
function filterContent(content: string) {
    let reg = /<[^>]+>/g;
    return content.replace(reg, '');
}

function updateNote() {
    if (!updateContent.value) return;
    loadingBar.start();
    usrUpdateNote({
        noteId: query.id,
        content: updateContent.value,
        topping: topping.value,
        title: userDtailList.value.title || '无标题',
        isImage: updateImage.value,
        imageUrl: userDtailList.value.imageUrl || ''
    }).then(res => {
        if (res.status === 200) {
            message.success(res.message);
            // 修改完后，返回列表定位修改过的数据
            editShow.value = !editShow.value;
            bus.emit('update-content', { height: query.height });
            loadingBar.start()
            nextTick(() => router.push('/'))
            return;
        }
        message.warning(res.message);
        editShow.value = !editShow.value;
        loadingBar.error()
    })
}

// 评论
async function hairComment() {
    if (commentValue.value) {
        let comment: Comment = {
            noteId: query.id as string,
            content: commentValue.value,
            createTime: new Date(),
            avatar: currentUserAvatar ?? '',
            alias: localStorage.getItem('designation') as string,
        }
        loadingBar.start();
        const result = await sendComment(comment);
        if (result.status === 401) {
            message.warning(result.message);
            commentValue.value = '';
            loadingBar.error();
            return;
        }
        console.info(result.data.createTime)
        let currenTemptData = {
            id: result.data.id,
            commentUserName: result.data.commentUserName,
            content: result.data.content,
            createTime: result.data.createTime,
            avatar: currentUserAvatar ?? '',
            alias: localStorage.getItem('designation') as string,
        }
        userDtailList.value.comment.push(currenTemptData);
        (currenTemptData as unknown) = null;
        obtainUserCommentComtent(query.id as string);
        commentValue.value = "";
        show.value = false;
        loadingBar.finish();
    }
}

function handerUpdateContent() {
    editShow.value = !editShow.value;
    updateImage.value = !updateImage.value;
    // topping.value = userDtailList.isTopping;
    userDtailList.value.html.forEach(item => {
        updateContent.value += item
        updateContent.value += '\n'
    });
    updateContent.value = filterContent(updateContent.value);
}

async function generateElement() {
    onteShow.value = true;
    const currentData = await findNote({ id: query.id as string });
    if (currentData.status !== 200) {
        currentData.value = []
        onteShow.value = false;
        return;
    }
    let splitContent = currentData.data.text.split(/[|\n]/);
    splitContent = splitContent.filter((item: string) => item !== '');
    userDtailList.value.title = currentData.data.title;
    userDtailList.value.html = splitContent;
    userDtailList.value.imageUrl = currentData.data.imageUrl ?? '';
    userDtailList.value.avatarName = currentData.data.noteUsername;
    userDtailList.value.createTime = currentData.data.createTime;
    topping.value = currentData.data.isTopping;
    onteShow.value = false;
    obtainUserCommentComtent(query.id as string);
}


function obtainUserCommentComtent(id: string) {
    commentShow.value = true;
    findUserCommentContent({
        noteId: id
    }).then(res => {
        console.info(res)
        userDtailList.value.comment = res.data;
        commentShow.value = false;
    })
}

// let currentHeight = ref(0);
onMounted(async () => {
    await generateElement();
    // 文章浏览记忆下版本迭代
    // window.scrollTo({
    //     top: currentHeight.value > 0 ? currentHeight.value : Number(sessionStorage.getItem('currentHeight')),
    //     behavior: "smooth"
    // });
    isFlag.value = true;
    // 此代码待优化
    window.addEventListener('scroll', () => {
        const params: any = { val: window.scrollY, child: isFlag.value }
        bus.emit('scrollTo-height', params);
        // sessionStorage.setItem('currentHeight', String(window.scrollY));
    })
    nextTick(() => {
        window.scrollTo(0, 0)
    })

})

onBeforeUnmount(() => {
    isFlag.value = false;
    window.removeEventListener('scroll', () => { })
})

</script>


<style lang="scss" scoped>
.container-details {
    padding-top: 20px;
    padding-left: 20px;
    padding-right: 20px;
    padding-bottom: 10px;
    background-color: #fff;


    .header-row {
        font-size: 22px;
        font-weight: 600;
        line-height: 1.31;
        color: #252933;
    }


}

.avaterName {
    text-align: right;
    color: rgb(189, 97, 116);
}

.item {
    display: flex;
    align-items: flex-start;
}

.bg {
    height: 10px;
    background-color: #f2f3f5;
}

.avatar {
    width: 28px;
    height: 28px;
    border-radius: 50%;
    margin-right: 10px;
}


.comment-container {
    padding-left: 10px;
    padding-right: 20px;
    background-color: #fff;
    margin-bottom: 80px;

    h2 {
        font-size: 16px;
    }


}

.comment-form {
    display: flex;
    position: relative;

    .avatar {
        margin-right: 12px;
        width: 40px;
        height: 40px;
        border-radius: 50%;
    }

    .form-box {
        flex: 1;
    }
}


.comment-item {
    display: flex;

    .avatar {
        margin-right: 12px;
        width: 40px;
        height: 40px;
        border-radius: 50%;
    }

    .info-box {
        flex: 1;

        p {
            font-size: 14px;
        }
    }

    .content-action {
        display: flex;
        justify-content: space-between;
        font-size: 12px;
    }
}

.text p {
    font-size: 14px;
    width: 100%;
    letter-spacing: 1px;
    margin: 20px 0;
    color: #2B2B2B;
    word-wrap: break-word;
}

.content-text {
    margin-left: 10rpx;
    font-size: 30rpx;
    background-image: -webkit-linear-gradient(right, rgb(105, 105, 208), #66ffff 10%, #18db0e 20%, #369c30 30%, #CCCCFF 40%, #00FFFF 50%, #CCCCFF 60%, #CC00CC 70%, #61ebf2 80%, #518787 90%, rgb(105, 105, 208) 100%);
    -webkit-text-fill-color: transparent;
    /* 字体设置成透明色 */
    background-clip: text;
    /* 裁剪背景，使文字作为裁剪区域向外裁剪 */
    background-size: 200% 100%;
    animation: masked-animation 4s linear infinite;
}

@keyframes masked-animation {
    0% {
        background-position: 0 0;
    }

    100% {
        background-position: -100% 0;
    }



}

.btn {
    transition: 1s;
}

.user-name {
    background-color: #80b4e8;
    padding: 2px;
    box-sizing: border-box;
    font-size: 9px;
    color: #fff;
}

.role-name {
    padding: 2px;
    box-sizing: border-box;
    font-size: 9px;
    background-color: #1f2d3a;
    color: #def202;
}
</style>